﻿using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp.Runtime.Session;
using SingleUserMall.Common;
using SingleUserMall.Complains.Form;
using SingleUserMall.Complains.VO;
using System.Linq;
using System.Threading.Tasks;

namespace SingleUserMall.Complains
{
    [AbpAuthorize]
    public class ComplainAppService : SingleUserMallAppServiceBase, IComplainAppService
    {
        private readonly IRepository<Complain,long> _complainRepository;
        public ComplainAppService(
            IRepository<Complain, long> complainRepository)
        {
            _complainRepository = complainRepository;
        }


        public async Task<PagedResultDto<ComplainViewVO>> GetComplainsAsync(PagedForm form)
        {
            var userId = AbpSession.GetUserId();
            var complains = _complainRepository.GetAll().Where(x => x.UserId == userId).OrderByDescending(x => x.CreationTime);
            return await complains.ToPagedResultDtoAsync<Complain, ComplainViewVO>(form, (f, vo) =>
            {
                vo.inUser = f.User;
            });
        }

        public async Task<ComplainViewVO> GetComplainAsync(SingleId<long> form)
        {
            var complain = await _complainRepository.FirstOrDefaultAsync(form.Id);
            return complain.ToVO<Complain, ComplainViewVO>((f, vo) =>
            {
                vo.inUser = f.User;
            });
        }

        public async Task PushComplainAsync(ComplainForm form)
        {
            var userId = AbpSession.GetUserId();
            var complain = form.MapTo<Complain>();
            complain.Status = ComplainVerifyStatus.WaitAudit;
            complain.UserId = userId;
            await _complainRepository.InsertAsync(complain);
        }

        public async Task<string> CheckComplainStatus()
        {
            var userId = AbpSession.GetUserId();
            var complain = await _complainRepository.FirstOrDefaultAsync(x => x.UserId == userId);
            if (complain == null)
            {
                return await Task.FromResult("未提交");
            }
            else
            {
                return await Task.FromResult(complain.Status.GetDescription());
            }
        }
    }
}
